package address

import (
	"encoding/json"
	"fmt"
	"gin/app/http/global"
	address2 "gin/app/http/model/address"
	"gin/app/http/response"
	"gin/app/http/struct/address"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
)

func GetAdressList(c *gin.Context) {
	rawBody, _ := ioutil.ReadAll(c.Request.Body)
	var params address.IndexParams
	err := json.Unmarshal(rawBody, &params)
	user_id := c.GetInt("user_id")
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	var arr []address2.Address
	var DB = global.DB
	result := DB.Where("user_id = ?", user_id).Find(&arr)
	if result.Error != nil {
		fmt.Println("Failed:", result.Error)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 1,
		"msg":  "请求成功!",
		"data": arr,
	})
}

func AddAdress(c *gin.Context) {
	rawBody, _ := ioutil.ReadAll(c.Request.Body)
	var params address.AddParams
	user_id := c.GetInt("user_id")
	err := json.Unmarshal(rawBody, &params)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	db := global.DB
	insertData := address2.Address{
		UserId:        user_id,
		RecipientName: params.RecipientName,
		PhoneNumber:   params.PhoneNumber,
		Province:      params.Province,
		City:          params.City,
		District:      params.District,
		Street:        params.Street,
		PostalCode:    params.PostalCode,
		IsDefault:     params.IsDefault,
	}
	if params.IsDefault == 1 {
		db.Model(&address2.Address{}).Where("user_id=?", params.UserId).Update("is_default", 0)
	}
	db.Create(&insertData)
	response.Success(c, "请求成功", gin.H{})
}

func Remove(c *gin.Context) {
	rawBody, _ := ioutil.ReadAll(c.Request.Body)
	var params address.RemoveParams
	err := json.Unmarshal(rawBody, &params)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	db := global.DB
	// 执行原生查询
	var addressLists address2.Address
	result := db.Delete(&addressLists, params.AddressId)
	if result.Error != nil {
		response.Fail(c, "请求失败", gin.H{})
	} else {
		response.Success(c, "请求成功", gin.H{})
	}
}

func Update(c *gin.Context) {

}
